package com.canto.common.support;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * # @PropertySourced注解读取yml配置文件时需要此解析类
 *
 * @author jsryin
 * @version 2021-07-02
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        factoryBean.setResources(encodedResource.getResource());
        factoryBean.afterPropertiesSet();
        Properties properties = factoryBean.getObject();
        String propertyName = StringUtils.isNotEmpty(name) ? name : encodedResource.getResource().getFilename();
        return new PropertiesPropertySource(propertyName, properties);
    }

}
